package com.boruishangge.common.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bloodcrown.baselib.permission.PermissionManage;
import com.boruishangge.common.APlusARoute;
import com.boruishangge.common.APlushConstant;
import com.boruishangge.common.R;
import com.boruishangge.common.databinding.ActivityWebviewViewBinding;
import com.boruishangge.common.uitls.WebViewJsApi;
import com.boruishangge.persagysdk.base.AppApplicationContext;
import com.boruishangge.persagysdk.base.BaseActivity;
import com.boruishangge.persagysdk.uitls.AppUtils;
import com.boruishangge.persagysdk.uitls.EmptyViewUtils.OnNetWorkRetryListener;
import com.boruishangge.persagysdk.uitls.EmptyViewUtils.ShowExceptionUIHelper;
import com.boruishangge.persagysdk.uitls.Logger;
import com.boruishangge.persagysdk.uitls.StringUtils;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.yxing.ScanCodeConfig;
import com.yxing.def.ScanMode;
import com.yxing.def.ScanStyle;

import wendu.dsbridge.OnReturnValue;


@Route(path = APlusARoute.aplus_webview_Router)
public class IbmsWebActivity extends BaseActivity {


    private ActivityWebviewViewBinding binding;
    private WebSettings settings;
    private String failiUrl;
    private long exitTime;

    @Autowired
    String Url;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_webview_view);
        ARouter.getInstance().inject(this);
        whiteStatusBar();
        initSetings();
        initShowExceptionView(binding.rvItem, new OnNetWorkRetryListener() {
            @Override
            public void retry() {

            }
        });
    }
    private void initSetings() {
        String url= APlushConstant.getWebUrl();
        if (StringUtils.checkNull(url)){
            Toast.makeText(this,"请输入地址",Toast.LENGTH_SHORT).show();
            return;
        }
        binding.wvWebview.loadUrl(url);
//        binding.wvWebview.loadUrl("file:///android  _asset/js-call-native.html");
        WebViewJsApi webViewJsApi=  new WebViewJsApi(this);
        webViewJsApi.setWindow(getWindow());
        binding.wvWebview.addJavascriptObject(webViewJsApi, null);
        settings = binding.wvWebview.getSettings();
        // 设置可以使用localStorage
        settings.setDefaultTextEncodingName("UTF-8");
        binding.wvWebview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                binding.progressBar.setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
            }
        });
          binding.wvWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                return super.shouldOverrideUrlLoading(webView, s);
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
                return super.shouldOverrideUrlLoading(webView, webResourceRequest);
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                binding.progressBar.setVisibility(View.VISIBLE);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                binding.progressBar.setVisibility(View.GONE);
            }
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                Logger.d("----aplus------", "证书错误: " + error);
                handler.proceed();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    binding.wvWebview.getSettings().setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
                }
            }



            // 旧版本，会在新版本中也可能被调用，所以加上一个判断，防止重复显示
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    return;
                }
                failiUrl = failingUrl;
                mShowExceptionUIHelper.setNotice_noContent("加载失败！请稍后再试");
                mShowExceptionUIHelper.refreshUI(ShowExceptionUIHelper.NETWORK_ERROR);

            }

            @Override
            public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                super.onReceivedError(webView, webResourceRequest, webResourceError);
                if (webResourceRequest.isForMainFrame()) {
                    failiUrl = webResourceRequest.getUrl().toString();
                    int statusCode = webResourceError.getErrorCode();
                    Logger.d("aplus----------------onReceivedHttpError code = " + statusCode);
                    mShowExceptionUIHelper.setNotice_noContent("加载失败！请稍后再试");
                    mShowExceptionUIHelper.refreshUI(ShowExceptionUIHelper.NETWORK_ERROR);


                }
            }
        });
        if (AppUtils.isDebugMode(AppApplicationContext.context)) {
            binding.wvWebview.setWebContentsDebuggingEnabled(true);
        } else {
            binding.wvWebview.setWebContentsDebuggingEnabled(false);
        }
        settings.setUserAgentString(settings.getUserAgentString() + "dxh_android_app");
        String appCaceDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
        settings.setAppCachePath(appCaceDir);//设置Application缓存API是否开启，默认false


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        //接收扫码结果
        if (requestCode == 3000) {

            if (PermissionManage.isHavePermission(this, Manifest.permission.CAMERA)) {
                goScanCodeActivity();
            } else {
                Toast.makeText(this, "请给相机权限", Toast.LENGTH_SHORT).show();
            }
        } else if(resultCode == RESULT_OK && requestCode == ScanCodeConfig.QUESTCODE && data != null){
            Bundle extras = data.getExtras();
            if(extras != null){
                String code = extras.getString(ScanCodeConfig.CODE_KEY);
                binding.wvWebview.callHandler("setScanCodeValue", new Object[]{code}, new OnReturnValue<String>() {
                    @Override
                    public void onValue(String retValue) {
                    }
                });
            }
        }
    }



    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Long secondTime = System.currentTimeMillis();
        if (secondTime - exitTime > 800) {
            Toast.makeText(AppApplicationContext.context, "再次点击退出", Toast.LENGTH_SHORT).show();
            //更新firstTime
            exitTime = secondTime;
            return;
        } else {//否则退出程序
            finish();
            System.exit(0);
        }
    }

    @Override
    public void finish() {
        ViewGroup view = (ViewGroup) getWindow().getDecorView();
        view.removeAllViews();
        super.finish();
    }

    private void back() {
        if (binding.wvWebview.canGoBack()) {
            binding.wvWebview.goBack();
        } else {
            finish();
        }
    }

    private void goScanCodeActivity() {
        ScanCodeConfig.create(this)
                //设置扫码页样式 ScanStyle.NONE：无  ScanStyle.QQ ：仿QQ样式   ScanStyle.WECHAT ：仿微信样式  ScanStyle.CUSTOMIZE ： 自定义样式
                .setStyle(ScanStyle.QQ)
                //扫码成功是否播放音效  true ： 播放   false ： 不播放
                .setPlayAudio(true)
                //设置音效音频
                .setAudioId(R.raw.beep)
                ////////////////////////////////////////////
                //以下配置 在style为 ScanStyle.CUSTOMIZE 时生效
                //设置扫码框位置  left ： 边框左边位置   top ： 边框上边位置   right ： 边框右边位置   bottom ： 边框下边位置   单位/dp
//                                    .setScanRect(new ScanRect(50, 200, 300, 450), false)
                //设置扫码框位置 scanSize : 扫码框大小   offsetX ： x轴偏移量    offsetY ：y轴偏移量   单位 /px
                .setScanSize(800, 0, -200)
                //是否显示边框上四个角标 true ： 显示  false ： 不显示
                .setShowFrame(true)
                //设置边框上四个角标颜色
                .setFrameColor(R.color.white)
                //设置边框上四个角标圆角  单位 /dp
                .setFrameRaduis(2)
                //设置边框上四个角宽度 单位 /dp
                .setFrameWith(4)
                //设置边框上四个角长度 单位 /dp
                .setFrameLenth(15)
                //设置是否显示边框外部阴影 true ： 显示  false ： 不显示
                .setShowShadow(true)
                //设置边框外部阴影颜色
                .setShaowColor(R.color.black_tran30)
                //设置扫码条运动方式   ScanMode.REVERSE : 往复运动   ScanMode.RESTART ：重复运动    默认ScanMode.RESTART
                .setScanMode(ScanMode.REVERSE)
                //设置扫码条扫一次时间  单位/ms  默认3000
                .setScanDuration(3000)
                //设置扫码条图片
                .setScanBitmapId(R.mipmap.scan_wechatline)
                //////////////////////////////////////////////
                .buidler()
                //跳转扫码页   扫码页可自定义样式
                .start(AplusScanCodeActivity.class);

    }
}
